package com.tanhua.dubbo.api;




import com.tan.model.mongo.Friend;
import com.tan.model.mongo.Movement;
import com.tan.model.vo.PageResult;
import com.tanhua.dubbo.utils.IdWorker;
import com.tanhua.dubbo.utils.TimeLinerService;
import org.apache.dubbo.config.annotation.DubboService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Sort;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.aggregation.Aggregation;
import org.springframework.data.mongodb.core.aggregation.AggregationResults;
import org.springframework.data.mongodb.core.aggregation.TypedAggregation;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;


import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@DubboService
public class MoventApiimpl implements MoventApi {
    @Autowired
    MongoTemplate mongoTemplate;
    @Autowired
    private IdWorker idWorker;
    @Autowired
    private TimeLinerService timeLinerService;
    @Override
    public void postMovement(Movement movement) {

        try {
            //1.保存动态详情
            Long id = idWorker.getNextId("movement");
            movement.setPid(id);
            Date date = new Date();
            Long created =  date.getTime();
            movement.setCreated(created);
            mongoTemplate.save(movement);
//            //2.查询当前用户的好友数据
//            Query query = Query.query(Criteria.where("userId").is(movement.getUserId()));
//            List<Friend> list = mongoTemplate.find(query, Friend.class);
//            Thread.sleep(10000);
//            //3.循环好友数据，构建时间线数据存入数据库
//            for (Friend friend : list) {
//                MovementTimeLine movementTimeLine = new MovementTimeLine();
//                movementTimeLine.setUserId(friend.getUserId());
//                movementTimeLine.setFriendId(friend.getFriendId());
//                movementTimeLine.setCreated(System.currentTimeMillis());
//                movementTimeLine.setMovementId(movement.getId());
//                mongoTemplate.save(movementTimeLine);
//
//            }
            timeLinerService.saveTimeLine(movement.getUserId(),movement);
        }catch(Exception e){
            e.printStackTrace();


        }

    }

    @Override
    public PageResult findUserid(Integer page, Integer pagesize, Long userId) {
      Query query = Query.query(Criteria.where("userId").is(userId));
      query.skip((page-1)*pagesize).limit(pagesize).
      with(Sort.by(Sort.Order.desc("created")));
      List<Movement> list = mongoTemplate.find(query, Movement.class);
       PageResult pageResult = new PageResult(page,pagesize, 0,list);
        return pageResult;
    }

    @Override
    public List<Movement> findFriendMovements(Integer page, Integer pagesize, Long userid) {
       Query query = Query.query(Criteria.where("userId").is(userid));
       query.skip((page-1)*pagesize).limit(pagesize);
       List<Friend> lists = mongoTemplate.find(query, Friend.class);
      List<Movement> list = new ArrayList<>();
      for (Friend friend : lists) {
          Query query1 = Query.query(Criteria.where("userId").is(friend.getFriendId()));
          List<Movement> list1 = mongoTemplate.find(query1, Movement.class);
          list.addAll(list1);
      }

        return list;
    }

    @Override
    public List<Movement> findFriendMovementsbyids(List<Long> ids) {
            Query query = Query.query(Criteria.where("pid").in(ids));
            List<Movement> list1 = mongoTemplate.find(query, Movement.class);
        return list1;
    }

    @Override
    public List<Movement> setRedisRecommendMovements(Integer pagesize) {
        //创建统计对象
        TypedAggregation aggregation = Aggregation.newAggregation(Movement.class,Aggregation.sample(pagesize));
        //调用mongoTemplate方法统计
     AggregationResults<Movement> results =   mongoTemplate.aggregate(aggregation,Movement.class);
        //获取统计对象
        return results.getMappedResults();
    }

    @Override
    public Movement getMovement(String id) {
        Query query = Query.query(Criteria.where("id").is(id));
        Movement movement = mongoTemplate.findOne(query, Movement.class);
        return movement;
    }

    @Override
    public List<Movement> findByUserId(Long uid, Integer state, Integer page, Integer pagesize) {

        if(state==null){
         Criteria criteria =Criteria.where("userId").is(uid);
            Query query=new Query(criteria).with(Sort.by(Sort.Direction.DESC,"created")).limit(pagesize).skip((page-1)*pagesize);
            List<Movement> list = mongoTemplate.find(query, Movement.class);
            return list;
        }else{
           Criteria criteria=Criteria.where("userId").is(uid).and("state").is(state);
            Query query=new Query(criteria).with(Sort.by(Sort.Direction.DESC,"created")).limit(pagesize).skip((page-1)*pagesize);
            List<Movement> list = mongoTemplate.find(query, Movement.class);
            return list;

        }

    }


}
